package servlet.dept;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;
import dao.DepartmentDao;
import dbutil.DBHelper;
import entity.Department;

public class CreateDeptServlet extends HttpServlet {

	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public CreateDeptServlet() {
		super();
	}

	public void destroy() {
		super.destroy();
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		JSONObject jsonObject = new JSONObject();
		DepartmentDao departmentDao = null;
		Date createDate = null;
		Department department = null;
		Connection conn = null;

		try {
			conn = DBHelper.getConnection();
			conn.setAutoCommit(false);
			departmentDao = new DepartmentDao();
			// createDate = sdf.parse(request.getParameter("createDate"));
			department = new Department();
			department.setDeptName(request.getParameter("deptName"));
			department.setCreateDate(new Date());
			
			if(departmentDao.saveOneDeparment(department)) {// 插入成功
				jsonObject.put("retCode", "1");
				conn.commit();
			} else {// 插入失败
				jsonObject.put("retCode", "0");
				jsonObject.put("desc", "创建部门出错");
				conn.rollback();
			}
			conn.setAutoCommit(true);
		} catch (Exception e) {
			e.printStackTrace();
			jsonObject.put("retCode", "0");
			jsonObject.put("desc", "CreateDeptServlet Exception");
		} finally {
			out.print(jsonObject.toString());
			out.close();
		}
	}

	public void init() throws ServletException {
	}

}